/**
 * 教师详情页面
 * /packageTeacher/pages/detail/index
 */

const Router = require('../../../utils/router')
const Storage = require('../../../utils/storage')
const Logger = require('../../../utils/logger')
const Track = require('../../../utils/track')
const Auth = require('../../../utils/auth')
const { TeacherService } = require('../../../services/index')

Page({
  data: {
    title: '教师详情',
    loading: true,
    teacherId: '',
    teacher: null,
    
    // 页面tab
    currentTab: 0,
    tabs: ['个人简介', '开设课程', '学员评价'],
    
    // 课程列表
    courses: [],
    coursesLoading: false,
    coursesHasMore: true,
    coursesPagination: {
      page: 1,
      limit: 10
    },
    
    // 评价列表
    reviews: [],
    reviewsLoading: false,
    reviewsHasMore: true,
    reviewsPagination: {
      page: 1,
      limit: 10
    },
    
    // 联系相关
    showContact: false
  },

  async onLoad(options) {
    const { id } = options
    this.setData({ teacherId: id })
    
    Logger.info('Page loaded: /packageTeacher/pages/detail/index', { teacherId: id })
    Track.trackPageView('/packageTeacher/pages/detail/index', { teacherId: id })
    
    await this.loadTeacherDetail()
  },

  /**
   * 加载教师详情
   */
  async loadTeacherDetail() {
    try {
      this.setData({ loading: true })
      
      // 调用API获取教师详情
      const teacher = await TeacherService.getTeacherDetail(this.data.teacherId)
      
      if (!teacher) {
        throw new Error('教师不存在')
      }
      
      this.setData({ teacher })
      
      // 设置导航栏标题
      wx.setNavigationBarTitle({
        title: teacher.name || '教师详情'
      })
      
      // 默认加载课程列表
      this.loadTeacherCourses()
      
      Track.trackEvent('teacher_detail_view', {
        teacher_id: this.data.teacherId,
        teacher_name: teacher.name
      })
      
    } catch (error) {
      Logger.error('Failed to load teacher detail', error)
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
      
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * 加载教师课程
   */
  async loadTeacherCourses(refresh = false) {
    if (refresh) {
      this.setData({
        'coursesPagination.page': 1,
        courses: [],
        coursesHasMore: true
      })
    }
    
    if (this.data.coursesLoading) return
    
    this.setData({ coursesLoading: true })
    
    try {
      const { coursesPagination } = this.data
      
      const params = {
        teacher_id: this.data.teacherId,
        page: coursesPagination.page,
        limit: coursesPagination.limit,
        status: 'active'
      }
      
      const result = await TeacherService.getTeacherCourses(params)
      const courses = Array.isArray(result) ? result : (result.courses || result.data || [])
      
      this.setData({
        courses: refresh ? courses : [...this.data.courses, ...courses],
        coursesHasMore: courses.length >= coursesPagination.limit
      })
      
    } catch (error) {
      Logger.error('Failed to load teacher courses', error)
    } finally {
      this.setData({ coursesLoading: false })
    }
  },

  /**
   * 加载教师评价 (暂时使用模拟数据，等待API完善)
   */
  async loadTeacherReviews(refresh = false) {
    if (refresh) {
      this.setData({
        'reviewsPagination.page': 1,
        reviews: [],
        reviewsHasMore: true
      })
    }
    
    if (this.data.reviewsLoading) return
    
    this.setData({ reviewsLoading: true })
    
    try {
      // 模拟评价数据，实际应调用API
      const mockReviews = [
        {
          id: 1,
          user: {
            name: '小雨',
            avatar: '/images/avatar1.jpg'
          },
          score: 5,
          content: '老师教得很仔细，动作分解得很清楚，零基础也能学会！',
          course: '零基础爵士舞入门',
          createTime: '2024-01-15 14:30:00',
          images: ['/images/review1.jpg']
        },
        {
          id: 2,
          user: {
            name: '小雅',
            avatar: '/images/avatar2.jpg'
          },
          score: 5,
          content: '老师很有耐心，课程内容很丰富，推荐给想学舞蹈的朋友们。',
          course: '现代舞基础课程',
          createTime: '2024-01-10 09:15:00',
          images: []
        }
      ]
      
      this.setData({
        reviews: refresh ? mockReviews : [...this.data.reviews, ...mockReviews],
        reviewsHasMore: false // 模拟数据，设为无更多
      })
      
    } catch (error) {
      Logger.error('Failed to load teacher reviews', error)
    } finally {
      this.setData({ reviewsLoading: false })
    }
  },

  /**
   * Tab切换
   */
  onTabChange(e) {
    const index = e.currentTarget.dataset.index
    this.setData({ currentTab: index })
    
    Track.trackClick('teacher_tab_change', 'navigation', { tab: this.data.tabs[index] })
    
    // 根据tab加载对应数据
    if (index === 1 && this.data.courses.length === 0) {
      this.loadTeacherCourses(true)
    } else if (index === 2 && this.data.reviews.length === 0) {
      this.loadTeacherReviews(true)
    }
  },

  /**
   * 课程项点击
   */
  onCourseItemTap(e) {
    const { id } = e.currentTarget.dataset
    Track.trackClick('teacher_course_item', 'navigation', { course_id: id })
    Router.navigateTo(`/packageTeacher/pages/courses/detail/index?id=${id}`)
  },

  /**
   * 显示联系方式
   */
  onShowContact() {
    if (!Auth.isLoggedIn()) {
      wx.showModal({
        title: '提示',
        content: '请先登录后查看联系方式',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            Router.navigateTo('/pages/login/index')
          }
        }
      })
      return
    }
    
    this.setData({ showContact: true })
    Track.trackClick('teacher_contact', 'action', { teacher_id: this.data.teacherId })
  },

  /**
   * 隐藏联系方式
   */
  onHideContact() {
    this.setData({ showContact: false })
  },

  /**
   * 拨打电话
   */
  onCallPhone() {
    const { teacher } = this.data
    if (!teacher?.phone) {
      wx.showToast({
        title: '暂无联系电话',
        icon: 'none'
      })
      return
    }
    
    wx.makePhoneCall({
      phoneNumber: teacher.phone,
      success: () => {
        Track.trackClick('teacher_call', 'contact', { teacher_id: this.data.teacherId })
      }
    })
  },

  /**
   * 微信联系
   */
  onWechatContact() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  /**
   * 查看所有课程
   */
  onViewAllCourses() {
    Track.trackClick('teacher_view_all_courses', 'navigation', { teacher_id: this.data.teacherId })
    Router.navigateTo(`/packageTeacher/pages/courses/list/index?teacher_id=${this.data.teacherId}&teacherName=${encodeURIComponent(this.data.teacher.name)}`)
  },

  /**
   * 课程列表滚动到底部
   */
  onCoursesReachBottom() {
    if (!this.data.coursesHasMore || this.data.coursesLoading) return
    
    this.setData({
      'coursesPagination.page': this.data.coursesPagination.page + 1
    })
    
    this.loadTeacherCourses()
  },

  /**
   * 评价列表滚动到底部
   */
  onReviewsReachBottom() {
    if (!this.data.reviewsHasMore || this.data.reviewsLoading) return
    
    this.setData({
      'reviewsPagination.page': this.data.reviewsPagination.page + 1
    })
    
    this.loadTeacherReviews()
  },

  /**
   * 分享教师
   */
  onShareAppMessage() {
    const { teacher } = this.data
    return {
      title: `${teacher?.name || '优秀教师'} - ${teacher?.title || '专业教师'}`,
      path: `/packageTeacher/pages/detail/index?id=${this.data.teacherId}`,
      imageUrl: teacher?.avatar || '/images/share-default.jpg'
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    const { teacher } = this.data
    return {
      title: `${teacher?.name || '优秀教师'} - ${teacher?.title || '专业教师'}`,
      path: `/packageTeacher/pages/detail/index?id=${this.data.teacherId}`,
      imageUrl: teacher?.avatar || '/images/share-default.jpg'
    }
  }
})
